package com.runfast.waimai.service.impl;

import com.runfast.common.service.BaseService;
import com.runfast.common.utils.DateUtils;
import com.runfast.common.dao.model.RunfastDeliverCost;
import com.runfast.paotui.entity.DeliveryCost;
import com.runfast.common.service.RunfastDeliverCostService;
import com.runfast.waimai.dao.mapper.RunfastBusinessMapper;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.web.dto.ActivityDto;
import com.runfast.waimai.web.dto.BusinessDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

<<<<<<< .mine
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
||||||| .r24
import javax.annotation.Resource;
import java.util.List;
=======
import java.math.BigDecimal;
import java.util.*;
>>>>>>> .r34

@Service
public class RunfastBusinessServiceImpl extends BaseService<RunfastBusiness, Integer, RunfastBusinessExample> implements RunfastBusinessService {


    @Autowired
    private RunfastActivityService activityService;

    @Autowired
    private RunfastFullLessService fullLessService;

    @Autowired
    private RunfastGoodsSellStandardService goodsSellStandardService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Override
    public RunfastBusinessMapper getMapper() {
        return (RunfastBusinessMapper)super.getMapper();
    }

    @Override
    public List<Map<String, Object>> nearBy(Integer agentId, Integer range, Double userLng, Double userLat, Integer sorting, Integer activityType, Integer catalogId, Pageable pageable) {

        Validate.notNull(agentId, "agentId不能为null");
        Validate.notNull(userLng, "userLng不能为null");
        Validate.notNull(userLat, "userLat不能为null");
        Validate.notNull(sorting, "sorting不能为null");

<<<<<<< .mine
  @Override
  public List<RunfastBusiness> findByAgentnameAndbusinessnameAndTime(Integer agentid, String name, Date createtime1, Date createtime2) {
    return dao.findByAgentnameAndbusinessnameAndTime(agentid, name, createtime1,createtime2);
  }
||||||| .r24
=======
        RunfastBusinessMapper businessMapper = getMapper();
        List<BusinessDto> businessDtoList = businessMapper.nearBy(agentId, range, userLng, userLat, sorting, activityType, catalogId, pageable);
>>>>>>> .r34

<<<<<<< .mine

||||||| .r24
=======

        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);

        List<Map<String, Object>> businessList = new ArrayList<>();
        for (BusinessDto businessDto : businessDtoList) {
            businessList.add(detail(defaultDeliveryTemplate, businessDto));
        }
        return businessList;
    }

    @Override
    public Map<String, Object> detail(Integer businessId, Double userLng, Double userLat) {
        Validate.notNull(businessId, "agentId不能为null");
        Validate.notNull(userLng, "userLng不能为null");
        Validate.notNull(userLat, "userLat不能为null");
        RunfastBusinessMapper mapper = getMapper();
        BusinessDto businessDto = mapper.detailWithDistance(businessId, userLng, userLat);

        Integer agentId = (Integer)businessDto.getAgentId();
        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);
        return detail(defaultDeliveryTemplate, businessDto);

    }

    /**
     * 根据配送模板计算商家
     * @param defaultDeliveryTemplate
     * @param businessDto
     * @return
     */
    @Override
    public Map<String, Object> detail(RunfastDeliverCost defaultDeliveryTemplate, BusinessDto businessDto) {
        /**
         *是否是新商户
         */


        Map<String, Object> businessMap = new HashMap<>();
        businessMap.putAll(BeanMap.create(businessDto));
        businessMap.put("newBusiness", false);
        if (businessDto.getCreateTime() != null) {
            Date date = new Date();
            Date createTime = (Date) businessDto.getCreateTime();
            long aa = createTime.getTime() + 864000000;
            if (date.getTime() < aa) {
                businessMap.put("newBusiness", true);
            }

        }

        if (StringUtils.isNotBlank(businessDto.getImgPath())) {

            String mini_imgPath = businessDto.getMini_imgPath();
            if (StringUtils.isBlank(mini_imgPath)) {
                businessMap.put("mini_imgPath", businessDto.getImgPath());
            }
        }

        /**
         * 计算当前商家参与的活动
         */
        Integer businessId = (Integer) businessDto.getId();

        //活动内容 1满减  2打折3赠品4特价5满减免运费6优惠券7免部分配送费8新用户立减活动9首单立减活动10商户红包11下单返红包
        ArrayList<Integer> typeList = new ArrayList<>();
        typeList.add(1);
        typeList.add(2);
        typeList.add(4);
        typeList.add(5);
        typeList.add(7);
        typeList.add(8);
        typeList.add(9);
        typeList.add(10);
        typeList.add(11);


        List<ActivityDto> activityList = businessDto.getActivityList();

        //活动分类
        HashMap<String, ActivityDto> activityTypeMap = new HashMap<>();


        //活动类型：1满减  2打折3赠品4特价5满减免运费6优惠券7免部分配送费8新用户立减活动9首单立减活动10商户红包11下单返红包
        for (ActivityDto activity : activityList) {
            if (activity.getPtype() != null) {
                Integer ptype = activity.getPtype();
                if (ptype == 1) {
                    //满减活动多个转换为一行显示
                    ActivityDto activityDto = putActivityIfNotExist(activityTypeMap, activity, "1");
                    Integer activityId = activityDto.getId();

                    RunfastFullLessExample fullLessExample = new RunfastFullLessExample();
                    fullLessExample.or().andActivity_idEqualTo(activityId);
                    fullLessExample.setOrderByClause("full asc");
                    List<RunfastFullLess> fullLessList = fullLessService.selectByExampleWithPageable(fullLessExample, PageRequest.of(0, 5));

                    activityDto.setFullLessList(fullLessList);


                } else if (ptype == 2) {
                    putActivityIfNotExist(activityTypeMap, activity, "2");
                    continue;

                } else if (ptype == 3) {
                    //没有赠送活动
                } else if (ptype == 4) {
                    putActivityIfNotExist(activityTypeMap, activity, "4");
                    continue;

                } else if (ptype == 5) {
                    putActivityIfNotExist(activityTypeMap, activity, "5");
                    continue;

                } else if (ptype == 6) {//6优惠券7免部分配送费8新用户立减活动9首单立减活动10商户红包11下单返红包
                    //没有优惠券
                } else if (ptype == 7) {
                    putActivityIfNotExist(activityTypeMap, activity, "7");
                    continue;

                }else if(ptype == 8){
                    putActivityIfNotExist(activityTypeMap, activity, "8");
                    continue;
                }else if(ptype == 9){
                    putActivityIfNotExist(activityTypeMap, activity, "9");
                    continue;
                }else if(ptype == 10){
                    putActivityIfNotExist(activityTypeMap, activity, "10");
                    continue;
                }else if(ptype == 11){
                    putActivityIfNotExist(activityTypeMap, activity, "11");
                    continue;
                }
            }


        }

        businessMap.put("activityMap", new ArrayList<>(activityTypeMap.values()));

        /**
         * 计算商家配送费和配送时间
         */
        int distance = ((Double) businessDto.getDistance()).intValue();//以米为单位
        Integer deliver = (Integer) businessDto.getIsDeliver();
        boolean isDeliver = deliver != null && deliver == 1 ? true : false;


        int deliveryDuration = 0;//配送时间（分）
        int deliveryFee = 0;//配送费
        if (isDeliver) {
            //自配送

            BigDecimal busshowps = (BigDecimal) businessDto.getBusshowps();
            if (busshowps == null || busshowps.compareTo(BigDecimal.valueOf(0)) == -1) {
                busshowps = BigDecimal.valueOf(0);
            }
            deliveryFee = busshowps.multiply(BigDecimal.valueOf(100)).intValue();

            Integer packTime = (Integer) businessDto.getPackTime();
            packTime = packTime == null ? 10 : packTime;
            Integer distributionTime = (Integer) businessDto.getDistributionTime();
            distributionTime = distributionTime == null ? 10 : distributionTime;
            deliveryDuration = packTime + distributionTime;

        } else {
            //代理商配送
            DeliveryCost deliveryCost = deliverCostService.getDeliveryCost(distance, null, defaultDeliveryTemplate);

            deliveryFee = deliveryCost.getDeliveryFee();

            Double speed = defaultDeliveryTemplate.getSpeed();
            int distributionTime = (int) Math.ceil(distance * 10 * speed / 1000);
            Integer packTime = (Integer) businessDto.getPackTime();
            packTime = packTime == null ? 10 : packTime;
            deliveryDuration = packTime + distributionTime;
            deliveryDuration = deliveryDuration < 25 ? 25 : deliveryDuration;//少于25分钟按照25分钟计算
        }
        businessMap.put("deliveryFee", deliveryFee);
        businessMap.put("deliveryDuration", deliveryDuration);


        /**
         * 计算商家营业状态
         */
        String weekday = (String) businessDto.getWorktoday();

        Date businessStart1 = (Date) businessDto.getStartTime1();
        Date businessEnd1 = (Date) businessDto.getEndTime1();
        Date businessStart2 = (Date) businessDto.getStartTime2();
        Date businessEnd2 = (Date) businessDto.getEndTime2();

        Date deliveryStart1 = defaultDeliveryTemplate.getStartTimeDay1();
        Date deliveryEnd1 = defaultDeliveryTemplate.getEndTimeDay1();
        Date deliveryStart2 = defaultDeliveryTemplate.getStartTimeNight2();
        Date deliveryEnd2 = defaultDeliveryTemplate.getEndTimeNight2();

        boolean open = DateUtils.isOpen(weekday, businessStart1, businessEnd1, businessStart2, businessEnd2, deliveryStart1, deliveryEnd1, deliveryStart2, deliveryEnd2, isDeliver);


        Integer status = (Integer) businessDto.getStatus();//后台设置商家营业状态
        Integer statu = (Integer) businessDto.getStatu();//商家设置营业状态

        if ((status != null && status == 1) || (statu != null && statu == 1)) open = false;
        businessMap.put("open", open);

        return businessMap;
    }

    /**
     * 每种活动类型，只保留第一个活动
     * @param activityTypeMap
     * @param activity
     * @param activityType
     * @return
     */
    private ActivityDto putActivityIfNotExist(HashMap<String, ActivityDto> activityTypeMap, ActivityDto activity, String activityType) {
        ActivityDto activityDto = activityTypeMap.get(activityType);
        if (activityDto != null) return activityDto;

        activityTypeMap.put(activityType, activity);
        return activity;
    }


    @Override
    public List<Map<String, Object>> search(String name, Integer agentId, Double userLng, Double userLat, Pageable pageable) {

        Validate.notNull(agentId, "name不能为null");
        Validate.notNull(agentId, "agentId不能为null");
        Validate.notNull(agentId, "userLng不能为null");
        Validate.notNull(agentId, "userLat不能为null");

        RunfastBusinessMapper businessMapper = getMapper();
        List<BusinessDto> businessDtoList = businessMapper.search(name, agentId,userLng, userLat, pageable);


        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);

        List<Map<String, Object>> businessList = new ArrayList<>();
        for (BusinessDto businessDto : businessDtoList) {
            Map<String, Object> detail = detail(defaultDeliveryTemplate, businessDto);


            RunfastGoodsSellExample goodsSellExample = new RunfastGoodsSellExample();
            goodsSellExample.or().andBusinessIdEqualTo(businessDto.getId()).andStatusEqualTo(0).andNameLike("%"+name+"%");
            goodsSellExample.or().andBusinessIdEqualTo(businessDto.getId()).andStatusIsNull().andNameLike("%"+name+"%");

            List<RunfastGoodsSell> goodsSellList = goodsSellService.search(name, businessDto.getId(), PageRequest.of(0, 5));

            detail.put("goodsSellList", goodsSellList);
            businessList.add(detail);
        }
        return businessList;
    }

    /**
     * 获取代理商下专区商家列表
     * @param activityId
     * @param pageable
     * @return
     */
    @Override
    public List<BusinessDto> getAgentZoneBusiness(Integer activityId, Double userLng, Double userLat, Pageable pageable){
        List<Integer> businessIdList = new ArrayList<>();;
        RunfastActivity activityWithTarget = activityService.getActivityWithTarget(activityId,pageable);
        List<RunfastActivityTarget> activityTargetList = activityWithTarget.getActivityTargetList();
        for (RunfastActivityTarget activityTarget : activityTargetList) {
            Integer businessId = activityTarget.getBusinessId();
            businessIdList.add(businessId);
        }




        List<BusinessDto> businessDtoList =getMapper().listBusiness(businessIdList, userLng, userLat);


        return businessDtoList;

    }

    @Override
    public BusinessDto detailWithDistance(Integer businessId, Double toLng, Double toLat) {
        return getMapper().detailWithDistance(businessId, toLng, toLat);
    }


>>>>>>> .r34
}